package db

import (
	"config/model"
	"flag"
	"github.com/nsqio/go-nsq"
	"github.com/redis/go-redis/v9"
	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/mongo"
	"gorm.io/gorm"
	"log"
	"strconv"
	"utilsx/db/gormUtils"
	"utilsx/db/influxUtils"
	"utilsx/db/mongoUtils"
	"utilsx/db/redisUtils"
	nsqUtils "utilsx/tools/nsq"
)

const (
	GameInfos  = "game_infos"
	UserDetail = "user_detail"
	OrderCart  = "order_cart"
)

var (
	CliName        = flag.String("port", "8080", "Exe Port")
	DbGorm         *gorm.DB
	RedisRdb       *redis.Client
	MongoDb        *mongo.Database
	MongoColl      = make(map[string]*mongo.Collection)
	NsqPublisher   *nsqUtils.NsqProducer
	NsqAddr        string
	InfluxdbClient *influxUtils.Client
	ConfigPath     string
)

func initConfig() {
	if MongoDb != nil {
		MongoColl[GameInfos] = MongoDb.Collection(GameInfos)
		MongoColl[UserDetail] = MongoDb.Collection(UserDetail)
		MongoColl[OrderCart] = MongoDb.Collection(OrderCart)
		mongoUtils.CreateIndex(MongoColl[UserDetail], bson.D{{"user_id", 1}})
		mongoUtils.CreateIndex(MongoColl[OrderCart], bson.D{{"order_id", 1}})
	}
	if DbGorm != nil {

	}
}
func InitTomlConfig() {
	config := model.DecodeFile(ConfigPath)
	for k, v := range config.Datasource {
		switch k {
		case "mongo":
			MongoDb = mongoUtils.CreatCon3(v.Username, v.Password, v.HostURL).Database(v.Database)
		case "mysql":
			DbGorm = gormUtils.CreateMysqlCon(v.Username, v.Password, v.HostURL, v.Database)
		case "redis":
			parseInt, err := strconv.ParseInt(v.Database, 10, 32)
			if err != nil {
				return
			}
			RedisRdb = redisUtils.CreatCon(v.HostURL, v.Password, "s", parseInt)
		default:
			log.Fatal("Other Datasource", k)
		}
	}
	NsqAddr = config.Nsq.HostURL
	NsqPublisher = nsqUtils.NewPublisher(NsqAddr).InitProducer(nsq.NewConfig())
	CliName = &config.Server.Port
	InfluxdbClient = influxUtils.NewInfluxClient(config.Influxdb.HostURL, config.Influxdb.Token).Init(config.Influxdb.Bucket, config.Influxdb.Org)
	initConfig()
}

func SetConfigPath(configPath string) {
	ConfigPath = configPath
	InitTomlConfig()
}
